<?php
include("common.php");

$page  = isset($_GET["page"])  && !empty($_GET["page"])  ? intval($_GET["page"])  : 1;
$site  = isset($_GET["site"])  && !empty($_GET["site"])  ? intval($_GET["site"])  : 0;
$sort  = isset($_GET["sort"])  && !empty($_GET["sort"])  ? intval($_GET["sort"])  : 1;
$range = isset($_GET["range"]) && !empty($_GET["range"]) ? intval($_GET["range"]) : 0;
$cate  = isset($_GET["cate"])  && !empty($_GET["cate"])  ? intval($_GET["cate"])  : 1;
$type  = isset($_GET["type"])  && !empty($_GET["type"])  ? trim($_GET["type"])    : "";
$num   = $type == "rss" ? 100 : 10;

//最多显示100页
$maxpage = floor(1000 / $num);
if($page > $maxpage) {
	$page = $maxpage;
}

if($word == "") {
	header("location:/");
	exit;
}

if($word) {
	$results = $sch->getSearchResults($word, $page, $num, $site ? array($site) : array(), $sort, $pos, $range, $cate);
}

$total = $results->total;
$start = ($page - 1) * $num;
$end   = $start + $num > $total ? $total : $start + $num;

$disk_filter    = $sch->getDiskFilter();
$sort_filter    = $sch->getSortFilter();
$size_filter    = $sch->getSizeFilter();
$last_searches  = $sch->getLastSearches(10);
$last_downloads = $sch->getLastDownloads(10);
$hot_searches   = $sch->getHotSearches();

$pager = new Pager("/search.php?word=".urlencode($word)."&site=$site&sort=$sort&range=$range&cate=$cate&page=<PAGE>", "<NUM>", $config["rewrite"], 100);
$pager->build($page, $num, $total);

$files = array();
foreach($results->data as $item) {
	$files[] = $word."-".$item->name;
}

$file_list = implode(",", $files);

$seo_description = str_replace(array("{keyword}", "{range}", "{file-list}"), array($word, "(".($total ? $start + 1 : 0)."-$end $total)", $file_list), $config["seo_search_description"]);

if(strlen($seo_description) < 60) {
	$seo_description .= " ".$config["seo_index_description"];
} 

$tpl->assign(array(
"disk_filter"=>$disk_filter,
"sort_filter"=>$sort_filter,
"size_filter"=>$size_filter,
"last_searches"=>$last_searches,
"hot_searches"=>$hot_searches,
"last_downloads"=>$last_downloads,
"results"=>$results,
"site"=>$site,
"sort"=>$sort,
"range"=>$range,
"cate"=>$cate,
"total"=>$total,
"start"=>$start,
"end"=>$end,
"second"=>$results->time,
"pager"=>$pager->html(10),
"seo_title"=>str_replace("{keyword}", $word, $config["seo_search_title"]). " (".($total ? $start + 1 : 0)." - $end $total)",
"seo_keywords"=>str_replace("{keyword}", $word, $config["seo_search_keywords"]),
"seo_description"=>$seo_description
));

if($type == "rss") {
	print '<?xml version="1.0" encoding="UTF-8" ?>';
	print "\n";
	$tpl->display("rss.xml");
} else {
	$tpl->assign("search_box", $tpl->fetch("search_box.html"));
	$tpl->assign("left", $tpl->fetch("left.html"));

	$tpl->display("header.html", "search.html", "footer.html");
}
?>